package com.dinner.model;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.dinner.util.PageHelper;

public class SellerDaoHibernate extends HibernateDaoSupport implements SellerDao {

	@Override
	public Seller getSellerByID(String sellerID) {
		SessionFactory sessionFactory = this.getSessionFactory();
		Session session = sessionFactory.openSession();
		int isolation = -1;
		try {
			isolation = session.connection().getTransactionIsolation();
			session.connection().setTransactionIsolation(
					Connection.TRANSACTION_SERIALIZABLE);
			session.beginTransaction();
			Seller seller = ((Seller) getHibernateTemplate().get(Seller.class,
					sellerID));
			session.getTransaction().commit();
			session.connection().setTransactionIsolation(isolation);
			return seller;
		} catch (Exception e) {
			e.printStackTrace();
			Transaction tx = session.getTransaction();
			if (tx.isActive())
				tx.rollback();
			return null;
		} finally {
			session.close();
		}
	}

	@Override
	public void saveSeller(Seller seller) {
		SessionFactory sessionFactory = this.getSessionFactory();
		Session session = sessionFactory.openSession();
		int isolation = -1;
		try {
			isolation = session.connection().getTransactionIsolation();
			session.connection().setTransactionIsolation(
					Connection.TRANSACTION_SERIALIZABLE);
			session.beginTransaction();
			session.save(seller);
			session.getTransaction().commit();
			session.connection().setTransactionIsolation(isolation);
		} catch (Exception e) {
			e.printStackTrace();
			Transaction tx = session.getTransaction();
			if (tx.isActive())
				tx.rollback();
		} finally {
			session.close();
		}
	}

	@Override
	public Seller getUserForLogin(String sellerID, String password) {
		Seller seller = getSellerByID(sellerID);
		if (seller != null && seller.getPassword().equals(password)
				&& seller.isAuthenticated()) {
			return seller;
		}
		return null;
	}

	@Override
	public void passAuthentication(String sellerID) {
		SessionFactory sessionFactory = this.getSessionFactory();
		Session session = sessionFactory.openSession();
		int isolation = -1;
		try {
			isolation = session.connection().getTransactionIsolation();
			session.connection().setTransactionIsolation(
					Connection.TRANSACTION_SERIALIZABLE);
			session.beginTransaction();
			String hql = "UPDATE FROM com.dinner.model.Seller seller SET seller.authenticated = true WHERE seller.sellerID = ?";
			org.hibernate.Query query = session.createQuery(hql)
					.setString(0, sellerID);
			query.executeUpdate();
			/*DinnerFactory factory = DinnerFactory.getFactory();
			MenuType mt = factory.newMenuType();
			
			mt.setDescription("");
			mt.setSellerID(sellerID);
			session.save(mt);*/
			session.getTransaction().commit();
			session.connection().setTransactionIsolation(isolation);
		} catch (Exception e) {
			e.printStackTrace();
			Transaction tx = session.getTransaction();
			if (tx.isActive())
				tx.rollback();
		} finally {
			session.close();
		}
	}

	@Override
	public void removeSeller(String sellerID) {
		SessionFactory sessionFactory = this.getSessionFactory();
		Session session = sessionFactory.openSession();
		int isolation = -1;
		try {
			isolation = session.connection().getTransactionIsolation();
			session.connection().setTransactionIsolation(
					Connection.TRANSACTION_SERIALIZABLE);
			session.beginTransaction();
			String hql = "DELETE FROM com.dinner.model.Seller seller WHERE seller.sellerID = ?";
			org.hibernate.Query query = session.createQuery(hql)
					.setString(0, sellerID);
			query.executeUpdate();
			session.getTransaction().commit();
			session.connection().setTransactionIsolation(isolation);
		} catch (Exception e) {
			e.printStackTrace();
			Transaction tx = session.getTransaction();
			if (tx.isActive())
				tx.rollback();
		} finally {
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Seller> getSellersByAuthentication(boolean authenticated) {
		SessionFactory sessionFactory = this.getSessionFactory();
		Session session = sessionFactory.openSession();
		int isolation = -1;
		try {
			isolation = session.connection().getTransactionIsolation();
			session.connection().setTransactionIsolation(
					Connection.TRANSACTION_SERIALIZABLE);
			session.beginTransaction();
			List<Seller> list = getHibernateTemplate().find(
					"from com.dinner.model.Seller seller where "
							+ "seller.authenticated = ?", authenticated);
			session.getTransaction().commit();
			session.connection().setTransactionIsolation(isolation);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return java.util.Collections.EMPTY_LIST;
		} finally {
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Seller> getAllSellers() {
		SessionFactory sessionFactory = this.getSessionFactory();
		Session session = sessionFactory.openSession();
		int isolation = -1;
		try {
			isolation = session.connection().getTransactionIsolation();
			session.connection().setTransactionIsolation(
					Connection.TRANSACTION_SERIALIZABLE);
			session.beginTransaction();
			List<Seller> list = getHibernateTemplate().find(
					"FROM com.dinner.model.Seller seller");
			session.getTransaction().commit();
			session.connection().setTransactionIsolation(isolation);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return java.util.Collections.EMPTY_LIST;
		} finally {
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Seller> SellersByPage(final PageHelper p) {
		SessionFactory sessionFactory = this.getSessionFactory();
		Session session = sessionFactory.openSession();
		int isolation = -1;
		try {
			isolation = session.connection().getTransactionIsolation();
			session.connection().setTransactionIsolation(
					Connection.TRANSACTION_SERIALIZABLE);
			session.beginTransaction();
			List<Seller> list = getHibernateTemplate().executeFind(
					new HibernateCallback() {
						@Override
						public Object doInHibernate(Session s)
								throws HibernateException, SQLException {
							Query query = s
									.createQuery("FROM com.dinner.model.Seller seller");
							query.setFirstResult((p.getCurrentPage() - 1)
									* p.getPageSize());
							query.setMaxResults(p.getPageSize());
							List list = query.list();
							query = s
									.createQuery("SELECT COUNT(*) FROM com.dinner.model.Seller");
							p
									.setTotalPage((((Integer) (query.iterate()
											.next())).intValue() - 1)
											/ p.getPageSize() + 1);
							return list;
						}
					});
			session.getTransaction().commit();
			session.connection().setTransactionIsolation(isolation);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return java.util.Collections.EMPTY_LIST;
		} finally {
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Seller> getSellersByAuthenticationAndPage(final boolean auth,
			final PageHelper p) {
		SessionFactory sessionFactory = this.getSessionFactory();
		Session session = sessionFactory.openSession();
		int isolation = -1;
		try {
			isolation = session.connection().getTransactionIsolation();
			session.connection().setTransactionIsolation(
					Connection.TRANSACTION_SERIALIZABLE);
			session.beginTransaction();
			List<Seller> list = getHibernateTemplate().executeFind(
					new HibernateCallback() {

						@Override
						public Object doInHibernate(Session s)
								throws HibernateException, SQLException {
							Query query = s
									.createQuery("FROM com.dinner.model.Seller seller WHERE seller.authenticated = ?");
							query.setParameter(0, auth);
							query.setFirstResult((p.getCurrentPage() - 1)
									* p.getPageSize());
							query.setMaxResults(p.getPageSize());
							List list = query.list();
							query = s
									.createQuery("SELECT COUNT(*) FROM com.dinner.model.Seller seller WHERE seller.authenticated = ?");
							query.setParameter(0, auth);
							p
									.setTotalPage((((Integer) (query.iterate()
											.next())).intValue() - 1)
											/ p.getPageSize() + 1);
							return list;

						}

					});
			/*
			 * .find( "from com.dinner.model.Seller seller where " +
			 * "seller.authenticated = ?", auth);
			 */
			session.getTransaction().commit();
			session.connection().setTransactionIsolation(isolation);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return java.util.Collections.EMPTY_LIST;
		} finally {
			session.close();
		}
	}
}
